package com.example.drools.controller;

import com.example.drools.dto.PricingRequest;
import com.example.drools.dto.SimplePricingRequest;
import com.example.drools.model.*;
import com.example.drools.service.PricingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 定价控制器
 */
@RestController
@RequestMapping("/api/pricing")
public class PricingController {

    @Autowired
    private PricingService pricingService;

    /**
     * 定价计算接口 - 简化版本用于前端
     */
    @PostMapping("/calculate")
    public List<PriceAdjustment> calculatePricing(@RequestBody SimplePricingRequest request) {
        UserProfile userProfile = new UserProfile();
        userProfile.setId(request.getProductId()); // 使用产品ID作为用户ID
        userProfile.setSegments(Set.of(request.getCustomerLevel()));
        userProfile.setRegion(request.getRegion());

        Context context = new Context();
        context.setPage("定价计算");
        context.setDevice("WEB");

        // 创建模拟分数数据
        List<Score> scores = List.of(
            new Score(request.getProductId(), "basePrice", request.getBasePrice()),
            new Score(request.getProductId(), "orderQuantity", request.getQuantity()),
            new Score(request.getProductId(), "season", getSeasonScore(request.getSeason()))
        );

        return pricingService.calculatePricing(userProfile, context, scores);
    }

    /**
     * 定价计算接口 - 完整版本
     */
    @PostMapping("/calculate-full")
    public List<PriceAdjustment> calculatePricingFull(@RequestBody PricingRequest request) {
        UserProfile userProfile = new UserProfile();
        userProfile.setId(request.getUserId());
        userProfile.setAge(request.getAge());
        userProfile.setSegments(new HashSet<>(request.getSegments()));
        userProfile.setRegion(request.getRegion());

        Context context = new Context();
        context.setPage(request.getPage());
        context.setDevice(request.getDevice());

        return pricingService.calculatePricing(userProfile, context, request.getScores());
    }

    private double getSeasonScore(String season) {
        switch (season) {
            case "WINTER": return 1.2; // 冬季涨价
            case "SUMMER": return 0.9; // 夏季降价
            case "SPRING":
            case "AUTUMN":
            default: return 1.0; // 正常价格
        }
    }

    /**
     * 快速定价计算接口
     */
    @PostMapping("/quick-calculate")
    public PriceAdjustment quickCalculate(@RequestParam String userId,
                                        @RequestParam String userType,
                                        @RequestParam double originalPrice,
                                        @RequestParam(defaultValue = "1") int orderQuantity) {
        return pricingService.quickCalculate(userId, userType, originalPrice, orderQuantity);
    }

    /**
     * 计算最终价格接口
     */
    @GetMapping("/final-price")
    public double calculateFinalPrice(@RequestParam String userId,
                                    @RequestParam String userType,
                                    @RequestParam double originalPrice,
                                    @RequestParam(defaultValue = "1") int orderQuantity) {
        return pricingService.calculateFinalPrice(userId, userType, originalPrice, orderQuantity);
    }

    /**
     * 获取用户可用折扣接口
     */
    @GetMapping("/discounts/{userId}")
    public List<PriceAdjustment> getAvailableDiscounts(@PathVariable String userId,
                                                      @RequestParam(defaultValue = "VIP") String userType,
                                                      @RequestParam(defaultValue = "商品页面") String page) {
        UserProfile userProfile = new UserProfile();
        userProfile.setId(userId);
        userProfile.setSegments(Set.of(userType));
        userProfile.setRegion("一线城市");

        Context context = new Context();
        context.setPage(page);
        context.setDevice("Web");

        return pricingService.getAvailableDiscounts(userProfile, context);
    }

    /**
     * 批量定价计算接口
     */
    @PostMapping("/batch-calculate")
    public List<PriceAdjustment> batchCalculate(@RequestBody List<UserProfile> userProfiles,
                                              @RequestParam(defaultValue = "批量定价") String page,
                                              @RequestParam(defaultValue = "100.0") double basePrice) {
        Context context = new Context();
        context.setPage(page);
        context.setDevice("API");

        return pricingService.batchCalculate(userProfiles, context, basePrice);
    }

    /**
     * 价格预览接口 - 展示不同用户类型的价格
     */
    @GetMapping("/preview")
    public List<PricePreview> pricePreview(@RequestParam double originalPrice) {
        String[] userTypes = {"VIP", "新用户", "普通用户"};
        List<PricePreview> previews = new ArrayList<>();

        for (String userType : userTypes) {
            PriceAdjustment adjustment = pricingService.quickCalculate("preview-user", userType, originalPrice, 1);
            double finalPrice = adjustment.calculateAdjustedPrice(originalPrice);
            
            PricePreview preview = new PricePreview();
            preview.setUserType(userType);
            preview.setOriginalPrice(originalPrice);
            preview.setFinalPrice(finalPrice);
            preview.setDiscount(adjustment.getDiscountPercentage());
            preview.setDescription(adjustment.getDescription());
            
            previews.add(preview);
        }

        return previews;
    }

    /**
     * 价格预览内部类
     */
    public static class PricePreview {
        private String userType;
        private double originalPrice;
        private double finalPrice;
        private int discount;
        private String description;

        // Getters and Setters
        public String getUserType() { return userType; }
        public void setUserType(String userType) { this.userType = userType; }
        
        public double getOriginalPrice() { return originalPrice; }
        public void setOriginalPrice(double originalPrice) { this.originalPrice = originalPrice; }
        
        public double getFinalPrice() { return finalPrice; }
        public void setFinalPrice(double finalPrice) { this.finalPrice = finalPrice; }
        
        public int getDiscount() { return discount; }
        public void setDiscount(int discount) { this.discount = discount; }
        
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
    }
}